package DAO;


import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.*;


/**
 *
 * @author tademir001
 */

public class DAO {
    
   Connection con;
    String url = "jdbc:mysql://localhost:3306/clinica";
    
    String user = "root";
    String password = "root";
    
    
    private String tipobanco;
    Statement stmt = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    public DAO(String tipobanco) {
        this.tipobanco = tipobanco;
    }

    public void conectarBanco() {
        try {
            if (this.tipobanco.equals("mysql")) {

                MysqlDataSource ds;
                ds = new MysqlDataSource();
                ds.setURL(url);
                ds.getConnection(user, password);
                this.con = ds.getConnection(user, password);
                this.stmt = con.createStatement();

            }


        } catch (SQLException ex) {
            ex.printStackTrace();
            throw new UnsupportedOperationException("Erro ao conectar no banco!");
        }


    }
    
    // Executa uma query
    public void executarQuery(String query){
        try {  
           this.rs = this.stmt.executeQuery(query); 
            
        } catch (SQLException ex) {
            
            ex.printStackTrace();
        }
    }
    
    // Prepara Insert
    public PreparedStatement preparaInsert(String insert){
        try {
            pstmt = con.prepareStatement(insert);
            
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        
        return pstmt;
    }
    
   // Prepara Update
   public PreparedStatement preparaUpdate(String update){
        try {
            pstmt = con.prepareStatement(update);
            
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        
        return pstmt;
    }
    
    // Desconecta o banco
    public void desconectarBanco(){
        try{
            
            if( this.con != null){
                this.con.close();
                this.con = null;
            }
        
            if( this.stmt != null){
                this.stmt.close();
                this.stmt = null;
            }
            
            if( this.pstmt != null){
                this.pstmt.close();
                this.pstmt = null;
            }
            
            if( this.rs != null){
                this.rs.close();
                this.rs = null;
            }
            
          
        } catch (SQLException ex) {
            
            ex.printStackTrace();
        }
    }
    
}